﻿#include "manager.h"

Manager::Manager(QMainWindow *parent)
    : QMainWindow(parent)
{

    srand((unsigned int)time(NULL));
    this->setWindowIcon(QPixmap(":/images/smarthome.png"));
    this->setWindowTitle("智能家居控制系统");
    QStatusBar *sbar = this->statusBar();
    connectedStatus = new QLabel;
    connectedStatus->setPixmap(QPixmap(":/images/switch_off.png"));
    sbar->addWidget(new QLabel("连接状态"));
    sbar->addWidget(connectedStatus);
    fuTcpServer = FuTcpServer::getTcpServer();
    QTabWidget *tabWidget = new QTabWidget;
    furnitureWidget = new FurnitureWidget(this);
    cameraWidget = new CameraWidget(this);
    musicWidget = new MusicWidget(this);
    tabWidget->addTab(furnitureWidget,"家居设备");
    tabWidget->addTab(cameraWidget,"监控设备");
    tabWidget->addTab(musicWidget,"音乐播放");
    this->setCentralWidget(tabWidget);
    connect(fuTcpServer,SIGNAL(signal_readData()),this,SLOT(slot_readData()));
    connect(fuTcpServer, &FuTcpServer::signal_connect,
            this, [this](bool isConnected) {
        if(isConnected) {
            connectedStatus->setPixmap(QPixmap(":/images/switch_on.png"));
        } else {
            connectedStatus->setPixmap(QPixmap(":/images/switch_off.png"));
        }
    });
    connect(tabWidget, &QTabWidget::currentChanged, this, &Manager::slot_tabChange);
}



void Manager::slot_readData()
{
    //读取数据
    QByteArray array = this->fuTcpServer->socket->readAll();
    //判断接收的指令
    bool ackValid = false;
    int ackType = array.left(3).toInt(&ackValid);
    if(!ackValid)
        return;
    //switch 判断不同指令，打开或关闭设备
    switch (ackType) {
    case Common::kitchenLampOpen:
        furnitureWidget->kitchenLampAfterOn(array.mid(3,1));
        break;
    case Common::kitchenLampClose:
        furnitureWidget->kitchenLampAfterOff(array.mid(3,1));
        break;
    case Common::diningRoomLampOpen:
        furnitureWidget->diningRoomLampAfterOn(array.mid(3,1));
        break;
    case Common::diningRoomLampClose:
        furnitureWidget->diningRoomLampAfterOff(array.mid(3,1));
        break;
    case Common::toiletLampOpen:
        furnitureWidget->toiletLampAfterOn(array.mid(3,1));
        break;
    case Common::toiletLampClose:
        furnitureWidget->toiletLampAfterOff(array.mid(3,1));
        break;
    case Common::secondBedroomLampOpen:
        furnitureWidget->secondBedroomLampAfterOn(array.mid(3,1));
        break;
    case Common::secondBedroomLampClose:
        furnitureWidget->secondBedroomLampAfterOff(array.mid(3,1));
        break;
    case Common::masterBedroomLampOpen:
        furnitureWidget->masterBedroomLampAfterOn(array.mid(3,1));
        break;
    case Common::masterBedroomLampClose:
        furnitureWidget->masterBedroomLampAfterOff(array.mid(3,1));
        break;
    case Common::studyRoomLampOpen:
        furnitureWidget->studyRoomLampAfterOn(array.mid(3,1));
        break;
    case Common::studyRoomLampClose:
        furnitureWidget->studyRoomLampAfterOff(array.mid(3,1));
        break;
    case Common::livingRoomLampOpen:
        furnitureWidget->livingRoomLampAfterOn(array.mid(3,1));
        break;
    case Common::livingRoomLampClose:
        furnitureWidget->livingRoomLampAfterOff(array.mid(3,1));
        break;
    case Common::kitchenVentilatorClose:
    case Common::kitchenVentilatorLow:
    case Common::kitchenVentilatorHigh:
    case Common::kitchenVentilatorLightOpen:
    case Common::kitchenVentilatorLightClose:
    case Common::kitchenVentilatorOpen:
        furnitureWidget->kitchenVentilatorAfter(array.mid(3,1));
        break;
    case Common::masterBedroomAirConditionerClose:
    case Common::masterBedroomAirConditionerCool:
    case Common::masterBedroomAirConditionerHeat:
    case Common::masterBedroomAirConditionerDehumidify:
    case Common::masterBedroomAirConditionerVentilate:
    case Common::masterBedroomAirConditionerOpen:
        furnitureWidget->masterBedroomAirAfter(array.mid(3,1));
        break;
    case Common::studyRoomAirConditionerClose:
    case Common::studyRoomAirConditionerCool:
    case Common::studyRoomAirConditionerHeat:
    case Common::studyRoomAirConditionerDehumidify:
    case Common::studyRoomAirConditionerVentilate:
    case Common::studyRoomAirConditionerOpen:
        furnitureWidget->studyRoomAirAfter(array.mid(3,1));
        break;
    case Common::livingRoomAirConditionerClose:
    case Common::livingRoomAirConditionerCool:
    case Common::livingRoomAirConditionerHeat:
    case Common::livingRoomAirConditionerDehumidify:
    case Common::livingRoomAirConditionerVentilate:
    case Common::livingRoomAirConditionerOpen:
        furnitureWidget->livingRoomAirAfter(array.mid(3,1));
        break;
    case Common::livingRoomTemperature:
        if(array.mid(3,1) == "1") { // 成功
            // 生成随机温度(18.0-28.0)
            double temp = 18.0 + rand() % 100 / 10.0;
            furnitureWidget->updateLivingRoomTemp(QString::number(temp, 'f', 1));
        } else { // 失败
            QMessageBox::critical(this, "操作失败", "获取客厅温度失败");
        }
        break;

    case Common::livingRoomHumidity:
        if(array.mid(3,1) == "1") { // 成功
            // 生成随机湿度(40-70)
            double humidity = 40 + rand() % 30;
            furnitureWidget->updateLivingRoomHumidity(QString::number(humidity, 'f', 1));
        } else { // 失败
            QMessageBox::critical(this, "操作失败", "获取客厅湿度失败");
        }
        break;

    case Common::masterBedroomTemperatureHumidity:
        if(array.mid(3,1) == "1") { // 成功
            // 获取完整的温湿度字符串
            QString dataStr = QString(array.mid(4)).trimmed();
            qDebug() << "Received master bedroom data:" << dataStr;

            // 解析温湿度值 - 格式应为 "湿度值％RH 温度值℃"
            QRegularExpression regex(R"((\d+\.?\d*)\s*%RH\s*(\d+\.?\d*)\s*℃)");
            QRegularExpressionMatch match = regex.match(dataStr);

            if (match.hasMatch()) {
                QString humidityStr = match.captured(1);
                QString tempStr = match.captured(2);

                bool ok1, ok2;
                double humidity = humidityStr.toDouble(&ok1);
                double temp = tempStr.toDouble(&ok2);
                // 添加调试信息，检查接收到的完整数据
                qDebug() << "Raw data:" << array;
                qDebug() << "Data hex:" << array.toHex();

                // 检查命令部分
                bool ackValid = false;
                int ackType = array.left(3).toInt(&ackValid);
                if(!ackValid) {
                    qDebug() << "Invalid command format";
                    return;
                }

                // 检查状态位
                QString status = array.mid(3,1);
                qDebug() << "Status:" << status;

                // 检查数据部分
                QString dataStr = QString(array.mid(4));
                qDebug() << "Data part:" << dataStr;

                if (ok1 && ok2) {
                    furnitureWidget->updateMasterRoomTemp(QString::number(temp, 'f', 1));
                    furnitureWidget->updateMasterRoomHumidity(QString::number(humidity, 'f', 1));
                } else {
                    QMessageBox::critical(this, "解析错误", "解析主卧温湿度数据失败");
                }
            } else {
                QMessageBox::critical(this, "数据错误",
                                      QString("主卧温湿度数据格式错误。接收到的数据: %1").arg(dataStr));
            }
        } else {
            QMessageBox::critical(this, "操作失败", "获取主卧温湿度失败");
        }
        break;

    case Common::masterBedroomHumidity:
        if(array.mid(3,1) == "1") { // 成功
            // 获取完整的湿度字符串
            QString dataStr = QString(array.mid(4));
            qDebug() << "Received master bedroom data:" << dataStr;

            // 解析湿度值
            QRegularExpression humidityRegex("(\\d+\\.?\\d*)℃");
            QRegularExpressionMatch humidityMatch = humidityRegex.match(dataStr);
            if (humidityMatch.hasMatch()) {
                QString humidityStr = humidityMatch.captured(1);
                bool ok;
                double humidity = humidityStr.toDouble(&ok);
                if (ok) {
                    furnitureWidget->updateMasterRoomHumidity(QString::number(humidity, 'f', 1));
                } else {
                    QMessageBox::critical(this, "解析错误", "解析主卧湿度失败");
                }
            } else {
                QMessageBox::critical(this, "数据错误", "主卧湿度数据格式错误");
            }
        } else {
            QMessageBox::critical(this, "操作失败", "获取主卧湿度失败");
        }
        break;

    case Common::masterBedroomTemperature:
        if(array.mid(3,1) == "1") { // 成功
            // 获取完整的温湿度字符串
            QString dataStr = QString(array.mid(4));
            qDebug() << "Received master bedroom data:" << dataStr;

            // 解析温度值
            QRegularExpression tempRegex("(\\d+\\.?\\d*)℃");
            QRegularExpressionMatch tempMatch = tempRegex.match(dataStr);
            if (tempMatch.hasMatch()) {
                QString tempStr = tempMatch.captured(1);
                bool ok;
                double temp = tempStr.toDouble(&ok);
                if (ok) {
                    furnitureWidget->updateMasterRoomTemp(QString::number(temp, 'f', 1));
                } else {
                    QMessageBox::critical(this, "解析错误", "解析主卧温度失败");
                }
            } else {
                QMessageBox::critical(this, "数据错误", "主卧温度数据格式错误");
            }
        } else {
            QMessageBox::critical(this, "操作失败", "获取主卧温度失败");
        }
        break;
    case Common::closeCamera:
        cameraWidget->openCameraAfterOff(array.mid(3,1));
        break;
    case Common::openCamera:
        cameraWidget->openCameraAfterOn(array.mid(3,1));
        break;
    case Common::captureImage:
        cameraWidget->imageCaptureAfter(array.mid(3,1));
        break;
    case Common::pauseMusic:
    case Common::playMusic:
        musicWidget->playMusicAfter(array.mid(3,1));
        break;
    case Common::nextMusic:
        musicWidget->nextMusicAfter(array.mid(3,1));
        break;
    case Common::prevMusic:
        musicWidget->prevMusicAfter(array.mid(3,1));
        break;
    default:
        qDebug() << "Unhandled command:" << this->fuTcpServer->command;
        break;
    }
}

void Manager::slot_tabChange(int index)
{
    // 处理离开上一个标签页的操作
    switch (lastTabIndex) {
    case 0: // 离开家居设备标签
        furnitureWidget->envTimer->stop();
        break;
    case 1: // 离开监控设备标签
        if (cameraWidget->isOpen) {
            cameraWidget->curCamera->stop();
            cameraWidget->viewFinder->hide();
            cameraWidget->openButton->setText("开启摄像头");
            cameraWidget->isOpen = false;
            cameraWidget->cameraLabel->clear();
        }
        break;
    case 2: // 离开音乐播放标签
        if (musicWidget->mPlayer->state() == QMediaPlayer::PlayingState) {
            QByteArray command = QByteArray::number(Common::pauseMusic);
            fuTcpServer->socket->write(command);
            musicWidget->mPlayer->pause();
            musicWidget->playButton->setIcon(QIcon(":/images/bfzn_004.png"));
            musicWidget->isPlay = false;

            // 停止音乐发送线程
            if (musicWidget->musicSendthread && musicWidget->musicSendthread->isRunning()) {
                musicWidget->musicSendthread->setStop(true);
                musicWidget->musicSendthread->quit();
                musicWidget->musicSendthread->wait();
            }
        }
        break;
    }

    // 处理进入新标签页的操作
    switch (index) {
    case 0: // 进入家居设备标签
        furnitureWidget->envTimer->start(5000);
        break;
    }

    // 更新最后标签索引
    lastTabIndex = index;
}

Manager::~Manager()
{

}
